<?php

namespace App\Modules\Admin\Entities\System;

use App\Models\Model;
use Illuminate\Support\Facades\Cache;

class SysAraeModel extends Model
{
    protected $table='sys_city';
    public $timestamps=false;
    protected $primaryKey='id';
    protected $is_delete=0;
    public $cache_key='sys:arae';

    /**
     * 获取子集分类查询条件
     * @return \think\model\relation\HasMany
     */
    public function children()
    {
        return $this->hasMany(self::class, 'parent_id', 'city_id')->order('id ASC');
    }
    public function getSelectCityLists($where =[])
    {
        $first = ['id','parent_id','name','name as text','area_code','area_code as value','level','area_code','merger_name','first'];
        return list_to_tree($this->where(['is_show'=>1])->whereIn('level',[1,2,3])->get($first)->toArray(),'id','parent_id');
//        return $this->where(['is_hidden'=>1])->get($first)->toArray();
    }

    /**
     * 获取城市数据完整列表
     */
    public function fullList($field = '*')
    {
        $first = ['id','parent_id','name','name as text','area_code','area_code as value','level','area_code','merger_name','first'];
        $allCity = $this->where(['is_show'=>1])->orderBy('area_code','asc')->get($first)->toArray();

        return $allCity;
    }


    public function getParentLists($params)
    {
        $parent_id = $params['pid']??0;
        $first = ['id','parent_id','name','area_code','level','area_code','merger_name','first'];
        return $this->where(['parent_id'=>$parent_id])->get($first)->toArray();
    }

    /**
     * 获取城市数据
     * @return mixed
     */
    public function cityList()
    {
        return Cache::remember('CITY_LIST', function () {
            $allCity = $this->getCityList([], 'city_id as v,name as n,parent_id');
            return sort_city_tier($allCity, 0);
        }, 0);
    }

    /**
     * 获取城市数据完整列表
     * @return mixed
     */
    public function getCache($get_type='')
    {
        if (!Cache::has($this->cache_key)) {
            $all = $this->fullList('*');
            $tree = list_to_tree($all, $this->getKeyName(), 'parent_id', 'children');
            Cache::set($this->cache_key, ['all' => $all, 'tree' => $tree]);
            return compact('all', 'tree');
        }else{
            return Cache::get($this->cache_key);
        }
    }
    /**
     * 获取所有文章数据
     *
     * @return array|mixed
     */
    public function getCacheAll()
    {
        return $this->getCache()['all'] ?? [];
    }
    public function getCacheTree()
    {
        return $this->getCache()['tree'] ?? [];
    }

}
